package com.lawliet.example.controller;


import com.lawliet.example.model.User;
import com.lawliet.example.model.auth.LoginUser;
import com.lawliet.example.model.system.SysUser;
import com.lawliet.example.model.vo.Result;
import com.lawliet.example.model.vo.UserDetailsImpl;
import com.lawliet.example.service.IUserService;
import com.lawliet.example.service.impl.CustomUserDetailsService;
import com.lawliet.example.service.system.SysUserService;
import com.lawliet.example.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证管理")
public class AuthController {

    @Value("${expire_time}")
    private Integer expire;

    @Autowired
    private SysUserService userService;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 注册用户
     * @param user
     * @return
     */
    @Operation(description = "注册用户",security = {@SecurityRequirement(name ="")})
    @PostMapping("/register")
    public Result<?> register(@RequestBody SysUser user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.save(user);
        return Result.OK("User registered successfully",user);
    }


    @Operation(summary = "登录用户",description = "返回登录用户信息")
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginUser loginUser) {
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();

        // 1. 封装用户名密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);

        // 2. 调用认证方法（会自动调用CustomUserDetailsService.loadUserByUsername ）
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        // 3. 认证成功，获取用户信息
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();

        String token = JwtUtil.createJWT(userDetails.getUser().getUsername());
        //token存入redis
        redisTemplate.opsForValue().set(token,username,expire, TimeUnit.MINUTES);

        userDetails.getUser().setToken(token);

        return Result.OK("查询成功！！！",userDetails);
    }

    @Operation(summary = "登出用户",description = "返回登录用户信息")
    @PostMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            //清空redis中的token信息
            redisTemplate.delete(token);
        }
        // 清空 SecurityContext
        SecurityContextHolder.clearContext();
        return Result.OK("退出成功");
    }
}
